<?php
namespace app\common\model;
use app\common\cache\CacheData;

class Coin extends Base
{
	
    public function cacheData(){
		$data = $this -> select();
		if($data){
			foreach($data as &$value):
				$value = $value->toArray();
			endforeach;
		}
		return $data;
	}

	/**
     * 货币缓存
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public static function coinData($id=null){
        $CACHE = CacheData::getInstance('Coin');
        $cacheData = $CACHE -> readCache();
        $data = [];
        foreach($cacheData as $cache):
            $data[$cache['id']] = $cache;
        endforeach;
        if(!is_null($id)){
            if(isset($data[$id]))
                return $data[$id];
            return
                false;
        }else{
            return $data;
        }
    }

    /**
     * 根据货币别名获取货币数据
     * @param  [type] $tagname [description]
     * @return [type]          [description]
     */
    public static function tagCoin($tagname){
        $cacheData = self::coinData();
        foreach($cacheData as $cache):
            if($cache['tag']==$tagname){
                return $cache;
            }
        endforeach;
        return false;
    }


    /**
     * 编辑
     * @return [type] [description]
     */
    public function editOneData($coin_name,$tag,$sort=0,$id){
        if($this->isExist($coin_name,$tag,$id)){
            $this->error = '货币名称或者货币别名已经存在';
            return false;
        }
        $this->save([
                'coin_name'=>$coin_name,
                'tag'=>$tag,
                'sort'=>$sort
            ],['id'=>$id]);
        return true;
    }

    /**
     * 添加一条数据
     */
    public function addOneData($coin_name,$tag,$sort=0){
        if($this->isExist($coin_name,$tag)){
            $this->error = '货币名称或者货币别名已经存在';
            return false;
        }
        $this->allowField(true)->save([
                'coin_name'=>$coin_name,
                'tag'=>$tag,
                'sort'=>$sort
            ]);
        return $this->getLastInsID();
    }

    public function delOneData($id){
        $data = $this->find($id);
        if($data){
            if($data['is_default']==1){
                $this->error = '默认货币无法删除';
                return false;
            }else{
                $this->where(['id'=>$id])->delete();
            }
        }else{
            $this->error='货币不存在';
            return false;
        }
    }

    private function isExist($coinName,$tag,$id=null){
        if(is_null($id)){
            $result = $this->where(['coin_name'=>$coinName])->whereOr(['tag'=>$tag])->find();
        }else{
            $result1 = $this->where(['coin_name'=>$coinName,'id'=>['<>',$id]])->find();
            $result2 = $this->where(['tag'=>$tag,'id'=>['<>',$id]])->find();
            $result = $result1||$result2?true:false;
        }
        if($result){
            return true;
        }else{
            return false;
        }
    }

}
